<template> 
    <!-- 根据 showButtons 的值决定是否显示 ul 元素 -->
    <ul v-if="showButtons" class = "drawing-panel">
        <!-- <li class="bmap-btn bmap-marker" id="marker" @click="draw($event.target)"></li> -->
        <li class="bmap-btn bmap-polyline" id="polyline" @click="draw($event.target)"></li>
        <li class="bmap-btn bmap-rectangle" id="rectangle" @click="draw($event.target)" ></li>
        <li class="bmap-btn bmap-polygon" id="polygon" @click="draw($event.target)"></li>
        <li class="bmap-btn bmap-circle" id="circle" @click="draw($event.target)"></li> 
    </ul>
    <!-- 根据 showButtons 的值决定是否显示清除围栏按钮 -->
    <button v-if="showButtons" @click = "removeOverlay()">清除围栏</button>
    <!-- 新增搜索框 -->
    <input style="margin-left: 15px" v-if="showButtons" type="text" v-model="searchKeyword" placeholder="输入关键词搜索" @keyup.enter="searchPlace">
    <a-button  size="small" style="height: 28px;border-radius: 0" :icon="h(SearchOutlined)" type="primary" v-if="showButtons" @click="searchPlace">搜索</a-button>
    <div  id="map"></div> 
</template>
<script lang="ts" setup name="BaiduMap">
import { onMounted, defineExpose, ref, defineEmits, defineProps, watch, h } from 'vue'
import { Button} from 'ant-design-vue';
import { SearchOutlined } from '@ant-design/icons-vue';
const emit = defineEmits(['overlaycomplete', 'clearPath', 'mapClick', 'addressReceived']); 
let map;
let drawingManager;
let overlays = [];
const path = ref<any[]>([]);
// 用于存储当前地图上的坐标图标
let currentMarker = null;  
// 新增搜索关键词
const searchKeyword = ref('');
// 新增本地搜索实例
let localSearch;
// 新增逆地理编码实例
let geocoder;

// 接收 path、bound 和 showButtons prop
const props = defineProps({
    path: {
        type: Array,
        default: () => []
    },
    bound: {
        type: Array,
        default: () => []
    },
    // 新增 showButtons 属性，用于控制显示隐藏
    showButtons: {
        type: Boolean,
        default: true
    }
})
console.log('bound',props.bound);
// 新增标志位，用于判断地图是否加载完成
const mapLoaded = ref(false);
// 新增标志位，用于控制是否允许在地图点击时绘制坐标点
const allowDrawMarker = ref(true);

function loadJScript() {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = '//api.map.baidu.com/api?type=webgl&v=3.0&ak=jhTHQbGNtlsmUgtlHjNSj07LjQAgqIdD&callback=init';
    document.body.appendChild(script);
}

const initMap = () => {
    // 创建实例
    map = new BMapGL.Map('map', { enableMapClick: false });
    // 设置地图中心以及缩放级别
    map.centerAndZoom(new BMapGL.Point(93.5142008, 42.817404), 14);
    map.enableScrollWheelZoom(true); 

    let styleOptions = {
        strokeColor: '#5E87DB',   
        fillColor: '#5E87DB',     
        strokeWeight: 2,          
        strokeOpacity: 1,         
        fillOpacity: 0.2          
    };

    map.addEventListener('click', function (e) {
        if (!allowDrawMarker.value) return; // 如果不允许绘制坐标点，则直接返回

        let BaiduBound = [];
        BaiduBound = [{lng:e.latlng.lng, lat:e.latlng.lat}];
        console.log(BaiduBound);

        // 清除之前的坐标图标
        if (currentMarker) {
            map.removeOverlay(currentMarker);
        }

        // 显示新的坐标图标
        const boundPoint = new BMapGL.Point(e.latlng.lng, e.latlng.lat);
        currentMarker = new BMapGL.Marker(boundPoint);
        map.addOverlay(currentMarker);

        // 调用逆地理编码获取地址
        geocoder.getLocation(boundPoint, function (rs) {
            const addComp = rs.addressComponents;
            const address = addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber;
            // console.log('地址:', address);
            // 发送地址数据给父组件
            emit('addressReceived', address);
        });

        // 发送 BaiduBound 数据给父组件
        emit('mapClick', BaiduBound);
    });

    let labelOptions = {
        borderRadius: '2px',
        background: '#FFFBCC',
        border: '1px solid #E1E1E1',
        color: '#703A04',
        fontSize: '12px',
        letterSpacing: '0',
        padding: '5px'
    };

    // 实例化鼠标绘制工具
    drawingManager = new BMapGLLib.DrawingManager(map, {
        isOpen: false,           
        enableCalculate: false,  
        enableSorption: true,    
        sorptiondistance: 20,    
        rectangleOptions: styleOptions,  
    }); 

    let overlaycomplete = function (e) {
        path.value = []; 
        overlays.push(e.overlay);
        var overlayPath = e.overlay.getPath();
        for (var i = 0; i < overlayPath.length; i++) {
            const point = {
                lng: overlayPath[i].lng,
                lat: overlayPath[i].lat
            };
            path.value.push(point); 
        }
        emit('overlaycomplete', path.value); 
        console.log(path.value);
        return path.value;
    };

    drawingManager.addEventListener('overlaycomplete', overlaycomplete);
    // 地图加载完成，设置标志位为 true
    mapLoaded.value = true;
    // allowDrawMarker.value = true;
    // 初始化本地搜索实例
    localSearch = new BMapGL.LocalSearch(map, {
        onSearchComplete: function(results) {
            if (localSearch.getStatus() === BMAP_STATUS_SUCCESS) {
                map.clearOverlays();
                for (let i = 0; i < results.getCurrentNumPois(); i++) {
                    const point = results.getPoi(i).point;
                    const marker = new BMapGL.Marker(point);
                    map.addOverlay(marker);
                }
            }
        }
    });
    // 初始化逆地理编码实例
    geocoder = new BMapGL.Geocoder();
}

// 监听 path 属性的变化
watch(() => props.path, (newpath) => {
    if (mapLoaded.value) { 
        if (newpath.length === 0) {
            if (map) {
                map.clearOverlays();
            }
            overlays = [];
            path.value = [];
        } else {
            if (map) {
                map.clearOverlays();
            }
            overlays = [];
            console.log('newpath', newpath);
            let styleOptions = {
                strokeColor: '#5E87DB',   
                fillColor: '#5E87DB',     
                strokeWeight: 2,          
                strokeOpacity: 1,         
                fillOpacity: 0.2          
            };
            const points = newpath.map(item => new BMapGL.Point(item.lng, item.lat));
            if (map) {
                const polygon = new BMapGL.Polygon(points, styleOptions);
                map.addOverlay(polygon);
                overlays.push(polygon);
            }
        }
    }
}, {
    immediate: true 
});

// 监听 bound 属性的变化，回显坐标并获取地址
watch(() => props.bound, (newBound) => {
    if (mapLoaded.value && newBound.length > 0) {
        console.log('newBound', newBound);

        // 清除之前的坐标图标
        if (currentMarker) {
            map.removeOverlay(currentMarker);
        }

        // 检查 newBound[0] 是否存在
        if (newBound[0] && newBound[0].lng && newBound[0].lat) {
            const { lng, lat } = newBound[0];
            const point = new BMapGL.Point(lng, lat);
            currentMarker = new BMapGL.Marker(point);
            map.addOverlay(currentMarker);

            // 调用逆地理编码获取地址
            geocoder.getLocation(point, function (rs) {
                const addComp = rs.addressComponents;
                const address = addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber;
                // 发送地址数据给父组件
                emit('addressReceived', address);
            });
        }
    }
}, {
    immediate: true
});

function draw(e) {
    if (map) {
        map.clearOverlays();
        // 清除当前标记
        currentMarker = null;
    }
    let arr = document.getElementsByClassName('bmap-btn');
    for (let i = 0; i < arr.length; i++) {
        arr[i].style.backgroundPositionY = '0';
    }
    e.style.backgroundPositionY = '-52px';
    let drawingType;
    switch (e.id) {
        case 'polyline': {
            drawingType = BMAP_DRAWING_POLYLINE;
            break;
        }
        case 'rectangle': {
            drawingType = BMAP_DRAWING_RECTANGLE;
            break;
        }
        case 'polygon': {
            drawingType = BMAP_DRAWING_POLYGON;
            break;
        }
        case 'circle': {
            drawingType = BMAP_DRAWING_CIRCLE;
            break;
        }
    }
    // 进行绘制
    if (drawingManager._isOpen && drawingManager.getDrawingMode() === drawingType) {
        drawingManager.close();
        allowDrawMarker.value = true; // 绘制完成，允许绘制坐标点
    } else {
        drawingManager.setDrawingMode(drawingType);
        drawingManager.open();
        allowDrawMarker.value = false; // 开始绘制，禁止绘制坐标点
    }
}

function removeOverlay() {
    if (map) {
        map.clearOverlays();
        // 清除当前标记
        currentMarker = null;
    }
    path.value = []; 
    emit('clearPath'); 
}

// 新增搜索方法
function searchPlace() {
    if (searchKeyword.value) {
        localSearch.search(searchKeyword.value);
    }
}

onMounted(() => {
    initMap();
    window.onload = loadJScript; 
})

defineExpose({
    map,
    drawingManager,
    initMap,
    path,
    overlays,
    mapLoaded // 暴露地图加载完成标志位
})

</script>
<style scoped lang="less">
#map {
    width: 100%;
    height: 600px;
}
ul li {list-style: none;}
.info {
    z-index: 999;
    width: auto;
    min-width: 22rem;
    padding: .75rem 1.25rem;
    margin-left: 1.25rem;
    position: fixed;
    top: 1rem;
    background-color: #fff;
    border-radius: .25rem;
    font-size: 14px;
    color: #666;
    box-shadow: 0 2px 6px 0 rgba(27, 142, 236, 0.5);
}
.drawing-panel {
    z-index: 999;
    position: fixed;
    bottom: 3.5rem;
    margin-left: 2.5rem;
    padding-left: 0;
    border-radius: .25rem;
    height: 47px;
    box-shadow: 0 2px 6px 0 rgba(27, 142, 236, 0.5);
}
.bmap-btn {
    border-right: 1px solid #d2d2d2;
    float: left;
    width: 64px;
    height: 100%;
    background-image: url(//api.map.baidu.com/library/DrawingManager/1.4/src/bg_drawing_tool.png);
    cursor: pointer;
}
.drawing-panel .bmap-marker {
    background-position: -65px 0;
}
.drawing-panel .bmap-polyline {
    background-position: -195px 0;
}
.drawing-panel .bmap-rectangle {
    background-position: -325px 0;
}
.drawing-panel .bmap-polygon {
    background-position: -260px 0;
}
.drawing-panel .bmap-circle {
    background-position: -130px 0;
}
</style>    